package se.perp.c4.model;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import se.perp.c4.model.Card.ECard;

public abstract class Deck {

    protected List<Card> deck;
    protected List<Card> discardPile = new ArrayList<Card>();
    private Card discardedMagic = null;

    public Deck() {
        deck = createDeck();
    }

    protected abstract List<Card> createDeck();


    public void discard(ECard which) {
        Card toRemove = null;
        for (Card c : getDeck()) {
            if (c.type == which) {
                toRemove = c;
                break;
            }
        }
        if (toRemove == null) {
            Logger.getLogger(Deck.class.getName()).warning(
                    "No such to discard: " + which);
            return;
        }

        deck.remove(toRemove);
        if (toRemove.type != ECard.MAGIC) {
            discardPile.add(toRemove);
        } else {
            discardedMagic = toRemove;
        }
    }

    public void resetIfNeeded() {
        if (isEmpty()) {
            reset();
        }
    }

    public void reset() {
        deck = createDeck();
        discardPile.clear();
    }

    public List<Card> getDeck() {
        return deck;
    }

    public boolean isEmpty() {
        return deck.size() == 0;
    }

    public int getCardCount() {
        return deck.size();
    }

    public int getDiscardedCount() {
        return discardPile.size();
    }

    public List<Card> getDiscardPile() {
        return discardPile;
    }

    public Card getCard(ECard which) {
        for (Card c : deck) {
            if (c.type == which) {
                return c;
            }
        }
        for (Card c : discardPile) {
            if (c.type == which) {
                return c;
            }
        }
        if (which == ECard.MAGIC) {
            return discardedMagic;
        }
        return null;
    }
}
